﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LibrarySync2.Settings;
using LibrarySync2.Business.Worker;
using System.IO;
using LibrarySync2.Common.Event;
using LibrarySync2.Common.Enum;

namespace LibrarySync2.Controls
{
    public partial class ucCreateLibraryFile : BaseUserControl
    {
        private LibraryAnalyzer _analyzer;

        protected string LibraryPath
        {
            get { return libraryPathSelector.Path; }
        }

        protected string LibraryFilePath
        {
            get { return libraryFileSelector.Path; }
        }

        public ucCreateLibraryFile()
        {
            InitializeComponent();
            LoadPreferences();
            UserPreferencesManager.PreferencesUpdated += new EventHandler<EventArgs>(UserPreferencesManager_PreferencesUpdated);
        }

        protected void UserPreferencesManager_PreferencesUpdated(object sender, EventArgs e)
        {
            LoadPreferences();
        }

        private void LoadPreferences()
        {
            libraryPathSelector.Path = UserPreferencesManager.Settings.DefaultMediaDirectory;
            libraryFileSelector.Path = UserPreferencesManager.Settings.DefaultLibraryFilePath;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (!ValidateInputs())
                return;

            PerformAnalysis();
        }

        private bool ValidateInputs()
        {
            if (string.IsNullOrEmpty(LibraryPath))
                return this.ShowErrorMessage("You must specify a library path.");

            if (!(new DirectoryInfo(LibraryPath)).Exists)
                return this.ShowErrorMessage("The specified library path does not exist.");

            if (string.IsNullOrEmpty(LibraryFilePath))
                return this.ShowErrorMessage("You must specify a POO file path.");

            return true;
        }

        private void PerformAnalysis()
        {
            _analyzer = new LibraryAnalyzer(LibraryPath, LibraryFilePath);
            _analyzer.LibraryAnalysisUpdate +=new EventHandler<LibraryAnalysisEventArgs>(Analyzer_LibraryAnalysisUpdate);
            btnCreate.Enabled = false;
            _analyzer.Start();
        }

        protected void Analyzer_LibraryAnalysisUpdate(object sender, LibraryAnalysisEventArgs eventArgs)
        {
            InvokeUpdateStatus(txtStatus, eventArgs.ToString());
            if (eventArgs.Status == LibraryAnalysisStatusType.Cancelled || eventArgs.Status == LibraryAnalysisStatusType.Complete)
                btnCreate.Enabled = true;
        }
    }
}
